package com.example.demo.controller;

import com.example.demo.entity.BookInfo;
import com.example.demo.entity.Cart;
import com.example.demo.entity.User;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.BookInfoService;
import com.example.demo.service.CartService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/cart")
public class CartController {

    @Resource
    private BookInfoService bookInfoService;

    @Resource
    private CartService cartService;

    @RequestMapping("/addition")
    public String cartlist(@RequestParam(defaultValue = "1",name="buyNum",required = false)int buyNum,
                           @RequestParam(defaultValue = "0",name = "book_id",required = false)Integer book_id,
                           HttpServletRequest request,
                           Model model ){

        //从session中取出cart购物车，若用户是第一次使用购物车，则cart为null
        Cart cart= (Cart) request.getSession().getAttribute("cart");
        //查询该书是否上架并且库存量是否充足，若均符合条件，则返回该实例对象，否则返回null
        BookInfo bookInfo=bookInfoService.findByIdAvailable(book_id,buyNum);
        if(bookInfo!=null){
            //将数量为buyNum的该书放到购物车中，并将购物车和该书信息存放到当前session中
            BSResult result=cartService.addToCart(bookInfo,cart,buyNum);
            request.getSession().setAttribute("cart",result.getData());
            request.getSession().setAttribute("bookInfo",bookInfo);



        }else{
            request.getSession().setAttribute("cart",null);
        }
        return "addcart";
    }


    @RequestMapping("/items")
    public String showCart(){
        return "cart";
    }

    @RequestMapping("/clear")
    public String clear(HttpServletRequest request){
        cartService.removeCart(request);
        return "cart";
    }

    @RequestMapping("/deletion/{book_id}")
    public String delete(@PathVariable("book_id")Integer book_id,HttpServletRequest request){

        cartService.deleteBook(book_id,request);
        return "cart";
    }



    @RequestMapping("/buy/num/update")
    @ResponseBody
    public BSResult update(Integer book_id,Integer newNum,HttpServletRequest request){
        return  cartService.updateNumById(book_id,newNum,request);
    }



}
